function my_plotPeriodBackground(X,Tag)
% my_plotPeriodBackground(X,Tag)
% -------- custom function ------
% description:
%	plot grey rectangle background as period indicator
% input:
%	X: double or timedate, series of x index
%	Tag: [0,1], 1 = grey indicator, 0 = none
% output:
%	no output, change current figure
% Author: Sid Chen
% Date: 2022/03/20

	check()
	% set area color to gray
	AreaColor = [0.7,0.7,0.7];
	% set area transparency
	AreaAlpha = 0.2;
	% get handle and x,y bound of figure
	handle_a = gca;
	Ylim = ylim;
	% get vertex position of background period
	[RecX,RecY] = getVertex();
	% draw
	fill(RecX,RecY,AreaColor,...
		'FaceAlpha',AreaAlpha,...
		'EdgeColor','none');

	% sort layer order, make grey rectangle as background
	sortLayerOrder();

	% custom function define
	function check()
		if isvector(X) && isvector(Tag)
			X = X(:);
			Tag = Tag(:);
		else
			error('Input must be vector!');
		end
	end
	function [REC_X,REC_Y] = getVertex()
		X_Step = mode(diff(X));
		% get start x of period
		if Tag(1) == 1
			Head = 1;
		else
			Head = [];
		end
		DiffX = diff(Tag);
		StartIndice = [Head;(find(DiffX == 1) +1)];

		% get end x of period
		if Tag(end) == 1
			Tail = numel(Tag);
		else
			Tail = [];
		end
		DiffX = diff(Tag);
		EndIndice = [find(DiffX == -1) ; Tail];

		REC_X = NaT(4,numel(StartIndice));
		REC_Y = NaN(4,numel(StartIndice));
		for ii = 1:numel(StartIndice)
			% get left,right,upper,lower bound of x,y of this rectangle
			start_x = X(StartIndice(ii)) - X_Step ./2;
			end_x = X(EndIndice(ii)) + X_Step ./2;
			lower_y = Ylim(1);
			upper_y = Ylim(2);
			% set vertex position of this rectangle
			REC_X(:,ii) = transpose([start_x, end_x, end_x, start_x]);
			REC_Y(:,ii) = transpose([lower_y,lower_y,upper_y,upper_y]);
		end
	end

	function sortLayerOrder()
		% sort layer order 
		Obj = handle_a.Children;
        TotalNumber = numel(Obj);
        for ii = 1:TotalNumber
            Class{ii} = class(Obj(ii));
        end
		IndiceArea = find(contains(Class,'Patch'));
		IndicePlot = find(~contains(Class,'Patch'));
		set(handle_a,'Children',Obj([IndicePlot,IndiceArea]));
	end
end
